﻿using INTEX.DataBase;
using INTEX.DataBase.Tools;
using INTEX.SCHEDULER;
using ReflectionStudio.Core.Events;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using WPFExcelReport.Helpers;
using WPFExcelReport.Controls;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for ProductionOrder.xaml
    /// TBList="ICC_STDMACHINE;ICC_QUERYTB;HRSTAMM;MKRF;AMSTAMM;ABPOS;ICC_ABAX;AMSTAMM;ICC_MKRF;ICC_PVKPOS;ICC_JWYARN;ABFOLGE;";//VWVKP
    /// </summary>
    public partial class VWVKP : UserControl
    {
        bool IsLoaded = false;
        #region-------------Properties-----------------------
        string lastDen = "8";
        string SType = "";//排产类型；
        JobBase Lastjob;
        ITXEXRPT ITXEXRPT;
        public ApplicationBase app
        {
            get
            {
                return ApplicationBase.Instance;
            }
        }
        INTEXDBC INTEXDBC
        {
            get
            {
                return app.INTEXDBC;
            }
        }

        public ITXSSPA Scheduler = new ITXSSPA();

        private readonly TaskScheduler _sync = TaskScheduler.FromCurrentSynchronizationContext();
        private NameScope pagescope = new System.Windows.NameScope();
        int year = 0, month = 0, day = 0;
        bool FilterByMachineType
        {
            get
            {
                if (chkMType.IsChecked == true)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        MainViewModel vm;
        public SETINTEXDB SetEnv
        {
            get
            {
                return vm.SetEnv;
            }
        }

        public SETINTEXDB SetData
        {
            get
            {
                return vm.SetData;
            }
        }
        public SETINTEXDB SetProd
        {
            get
            {
                return vm.SetProd;
            }
        }
        #region=====vwAMSTAMM=======
        CollectionViewSource vwAMSTAMM
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwAMSTAMM");
            }
        }
        DataRow dwAMSTAMM
        {
            get
            {
                if (vwAMSTAMM.View == null)
                    return null;
                if ((DataRowView)vwAMSTAMM.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwAMSTAMM.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwBMKRF=======
        CollectionViewSource vwBMKRF
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwMKRF");
            }
        }
        DataRow dwBMKRF
        {
            get
            {
                if (vwBMKRF.View == null)
                    return null;
                if ((DataRowView)vwBMKRF.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwBMKRF.View.CurrentItem).Row;
            }
        }
        #endregion


        BindingListCollectionView cvABP
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(dlgABP.ItemsSource);
            }
        }

        string KRS
        {
            get
            {
                return vm.ABKRS;
            }
            set
            {
                vm.ABKRS = value;
            }
        }
        string LFD
        {
            get
            {
                return vm.ABLFD;
            }
            set
            {
                vm.ABLFD = value;
            }
        }
        string POS
        {
            get
            {
                return vm.ABPOS;
            }
            set
            {
                vm.ABPOS = value;
            }
        }
        string MKFTP
        {
            get
            {
                return vm.MKFTP;
            }
            set
            {
                vm.MKFTP = value;
            }
        }

        string KSTKRS
        {
            get
            {
                return vm.KSTKRS;
            }
            set
            {
                vm.KSTKRS = value;
            }
        }
        string KST
        {
            get
            {
                return vm.KST;
            }
            set
            {
                vm.KST = value;
            }
        }
        string AGANG
        {
            get
            {
                return vm.AGANG;
            }
            set
            {
                vm.AGANG = value;
            }
        }
        string AMTYP
        {
            get
            {
                return vm.AMTYP;
            }
            set
            {
                vm.AMTYP = value;
            }
        }

        #endregion
        public VWVKP()
        {
            InitializeComponent();
            Scheduler.MODE = "P";
        }
        public void SetUp(Dictionary<string, object> dicParamater)
        {



        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            DataSet SResult;
            try
            {
                if (DesignerProperties.GetIsInDesignMode(this))
                    return;
                if (IsLoaded)
                    return;
                IsLoaded = true;
                NameScope.SetNameScope(this, pagescope);
                vm = (MainViewModel)this.DataContext;
                ITXEXRPT = new ITXEXRPT();
                ITXEXRPT.Root = "C:\\IntexReport";
                ITXEXRPT.strCompany = app.company;
                ITXEXRPT.PrintType = "OpenExcel";
                txtABPAUFKRS.Text = "T2";
                txtABPAUFLFD.Text = "001336";
                txtABPAUFPOS.Text = "002";
                Density.Text = "8";
                ComboBoxItem item;
                switch (app.company)
                {
                    case "YGR":
                        item = new ComboBoxItem();
                        item.Content = "纺纱";
                        cmbStype.Items.Add(item);
                        cmbStype.Text = "纺纱";
                        break;
                    case "JLT":
                        item = new ComboBoxItem();
                        item.Content = "色织";
                        cmbStype.Items.Add(item);
                        cmbStype.Text = "色织";
                        break;
                }

                cmbStype.Items.MoveCurrentToFirst();
                vwBMKRF.View.CurrentChanged += vwBMKRF_CurrentChanged;
                cvABP.CustomFilter = "JOBTYPE<>'X'";
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return;

        }
        public delegate DataSet AsyncRunHandle(object p1 = null, object p2 = null, object p3 = null, object p4 = null, object p5 = null);
        string _sTemp = string.Empty;

        public void AsyncRun(string TaskType, object p1 = null, object p2 = null, object p3 = null, object p4 = null, object p5 = null)
        {
            AsyncRunHandle fHandle = null;
            AsyncCallback callback = null;
            IAsyncResult aResult = null;
            WaitHandle waitHandle = null;
            switch (TaskType)
            {
                case "StartPlan":
                    fHandle = new AsyncRunHandle(Scheduler.StartPlan);
                    break;
            }
            if (fHandle != null)
            {
                callback = new AsyncCallback(this.AsyncCallbackImpl);
                aResult = fHandle.BeginInvoke(p1, p2, p3, p4, p5, callback, fHandle);
                waitHandle = aResult.AsyncWaitHandle;
                waitHandle.WaitOne();
            }
        }
        public void AsyncCallbackImpl(IAsyncResult run)
        {
            try
            {
                AsyncRunHandle handle = run.AsyncState as AsyncRunHandle;
                DataSet SResult = handle.EndInvoke(run);
                switch (handle.Method.Name)
                {
                    case "StartPlan":
                        Task.Factory.StartNew(() => btnShow_Click(null, null), new CancellationTokenSource().Token, TaskCreationOptions.None, _sync).Wait();
                        break;
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            //异步执行更新数据库，
            //完成后，异步执行查询
            if (cmbStype.SelectedIndex == -1)
            {
                MessageBox.Show("请选择排产类型。");
                return;
            }
            AsyncRun(SType, KSTKRS, KST, AGANG);
        }
        public void ShowDetail()
        {
            try
            {
                RemoveAllJobs();
                DataSet Result = new DataSet();
                vm.BuildData();
                Scheduler.PrepareAllJob(SetEnv, false);
                AsyncRun("StartPlan", SetProd, SetEnv, SetData, MachinesLib, JobsLib);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnShow_Click(object sender, EventArgs e)
        {
            try
            {
                Scheduler.ShowMachine();
                if (vwBMKRF != null)
                {
                    if (vwBMKRF.View != null)
                    {
                        vwBMKRF.View.MoveCurrentToFirst();
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void AM_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (dwAMSTAMM == null)
                return;
            Machine machine = (Machine)this.FindName("mx" + dwAMSTAMM["MACHINEID"].ToString());
            if (machine != null)
            {
                FocusMachine(mainViewer, machines, machine);
            }
        }



        private void btnPrint_Click(object sender, EventArgs e)
        {
            ITXEXRPT.dsSource = SetEnv; ;
            ITXEXRPT.DocType = "JLTAVDOC";
            ITXEXRPT.strExcelFile = @"JLT\JLTAV37.xls";
            ITXEXRPT.WriteExcelReport();
        }

        private void cmbStype_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataSet SResult = new DataSet();
            try
            {
                ComboBoxItem item = e.AddedItems[0] as ComboBoxItem;
                switch (item.Content.ToString().Trim())
                {
                    case "纺纱":
                    default:
                        SType = "SpinningPlanDB";
                        KSTKRS = "99";
                        KST = "9999";
                        AGANG = "999";
                        AMTYP = "99999999";
                        break;
                    case "色织":
                        SType = "SpinningPlanDB";
                        KSTKRS = "99";
                        KST = "9999";
                        AGANG = "999";
                        AMTYP = "99999999";
                        break;
                }

                SetEnv.Clear();
                vm.LoadEnv();

            }
            catch (Exception ex)
            {
                SetEnv.Clear();
                SetEnv.Merge(SResult);
            }
            finally
            {
                SetupMachine();
            }
        }


        private void btnShowExt1_Click(object sender, RoutedEventArgs e)
        {
            if (ZoneExt1.Visibility == Visibility.Collapsed)
            {
                ZoneExt1.Visibility = Visibility.Visible;
                return;
            }
            if (ZoneExt1.Visibility == Visibility.Visible)
            {
                ZoneExt1.Visibility = Visibility.Collapsed;
                return;
            }
        }
        private void btnShowExt2_Click(object sender, RoutedEventArgs e)
        {
            if (ZoneExt2.Visibility == Visibility.Collapsed)
            {
                ZoneExt2.Visibility = Visibility.Visible;
                return;
            }
            if (ZoneExt2.Visibility == Visibility.Visible)
            {
                ZoneExt2.Visibility = Visibility.Collapsed;
                return;
            }
        }
        private void btnShowExt3_Click(object sender, RoutedEventArgs e)
        {
            if (ZoneExt3.Visibility == Visibility.Collapsed)
            {
                ZoneExt3.Visibility = Visibility.Visible;
                return;
            }
            if (ZoneExt3.Visibility == Visibility.Visible)
            {
                ZoneExt3.Visibility = Visibility.Collapsed;
                return;
            }
        }

        private void btnEditJob_Click(object sender, RoutedEventArgs e)
        {
            if (dwBMKRF == null)
            {
                MessageBox.Show("请选择任务");
                return;
            }
            string JobID = "Job" + dwBMKRF["ABAID"].ToString();
            JobBase job = (JobBase)JobsLib[JobID];
            JobDetailWindow JobDetailWindow = new JobDetailWindow();
            JobDetailWindow.DataContext = job.DataContext;
            JobDetailWindow.Show();
        }

    }
}
